package com.atguigu.exer;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author yihu
 * @create 2021-06-03 16:25
 * @email:1057202547@qq.com
 * @dec: 图片加密
 */
public class PicTest {

    //图片加密
    @Test
    public  void test1(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(new File("snipaste_20200617_145159.png"));
            fos = new FileOutputStream(new File("snipaste_20200617_145159_secret.png"));

            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer))!=-1){
                //对字节数组进行加密
                //for (byte b:buffer){
                //  b = (byte) (b^5);
                //} 错误的写法，buffer中的元素赋值给了另外一个变量b，buffer中的元素并没有进行修改
                for (int i = 0; i < len; i++) {
                    buffer[i] = (byte) (buffer[i]^5);
                }
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //解密图片
    @Test
    public  void test2(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(new File("snipaste_20200617_145159_secret.png"));
            fos = new FileOutputStream(new File("解密图.png"));
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer))!=-1){
                //对字节数组进行加密
                //for (byte b:buffer){
                //  b = (byte) (b^5);
                //} 错误的写法，buffer中的元素赋值给了另外一个变量b，buffer中的元素并没有进行修改
                for (int i = 0; i < len; i++) {
                    buffer[i] = (byte) (buffer[i]^5);
                }
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
